package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 管理员登录
     *
     * @param map
     * @return
     */
    public ResponseEntity login(Map map) {
        //1、获取请求得参数(username,password,verificationCode（验证码）,uuid)
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //2、判断用户名和密码是否为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            //抛出异常
            //throw new BusinessException("用户名或密码为空");
            Map m = new HashMap();
            m.put("message", "用户名或密码为空");
            return ResponseEntity.status(500).body(m);
        }
        //3、判断验证码是否为空
        if (StringUtils.isEmpty(verificationCode)) {
            throw new BusinessException("验证码为空");
        }
        //4、获取redis中得验证码比对
        String code = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (StringUtils.isEmpty(code) || !verificationCode.equals(code)) {
            throw new BusinessException("验证码错误");
        }

        //验证码只能用一次
        redisTemplate.delete(Constants.CAP_CODE + uuid);
        //5、根据用户名查询用户名和密码
        password = SecureUtil.md5(password);//密码md5加密
        Admin admin = adminMapper.selectOne(
                Wrappers.<Admin>lambdaQuery()
                        .eq(Admin::getUsername, username)
                        .eq(Admin::getPassword, password)
        );

        if (admin == null) {
            throw new BusinessException("用户名或者密码");
        }

        //6、用工具类生成token并返回给前端
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("username", username);
        claims.put("id", admin.getId());
        String token = JwtUtils.getToken(claims);
        //7、构造返回值
        Map res = new HashMap();
        res.put("token", token);
        //删除验证码
        redisTemplate.delete(Constants.CAP_CODE + uuid);
        return ResponseEntity.ok(res);

    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public AdminVo profile() {

        Long id = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(id);
        return AdminVo.init(admin);
    }
}
